import { Renderer } from "@k8slens/extensions";

import { tool } from "@langchain/core/tools";
import { z } from "zod";
const {
  Catalog: { CatalogEntityRegistry },
} = Renderer;
import { KubeConfig, CoreV1Api } from "@kubernetes/client-node";
import { llmPreferenceStore } from "../../llm/preference/llm-preference-store";

const getPodLogTool = tool(
  async ({
    name,
    namespace,
  }: {
    name: string;
    namespace: string;
  }): Promise<string> => {
    console.log("name=", name);
    console.log("namespace=", namespace);
    const kubeconfigPath = new CatalogEntityRegistry().activeEntity.spec
      .kubeconfigPath;
    const kc = new KubeConfig();
    kc.loadFromFile(kubeconfigPath);

    const k8sApi = kc.makeApiClient(CoreV1Api);
    const log = await k8sApi.readNamespacedPodLog(
      name,
      namespace,
      null,
      false,
      true,
      llmPreferenceStore.podLogMaxLength,
    );
    return log.body;
  },
  {
    name: "get_pod_log",
    description: "Get the Pod log by Pod Name And Namespace",
    schema: z.object({
      name: z.string().describe("The name of the Pod"),
      namespace: z.string().describe("The namespace of the Pod"),
    }),
    verbose: true,
  }
);

const getPodPreFailLogTool = tool(
  async ({
    name,
    namespace,
  }: {
    name: string;
    namespace: string;
  }): Promise<string> => {
    console.log("name=", name);
    console.log("namespace=", namespace);
    const kubeconfigPath = new CatalogEntityRegistry().activeEntity.spec
      .kubeconfigPath;
    const kc = new KubeConfig();
    kc.loadFromFile(kubeconfigPath);

    const k8sApi = kc.makeApiClient(CoreV1Api);

    let log = { body: "" };
    try {
      log = await k8sApi.readNamespacedPodLog(
        name,
        namespace,
        null,
        false,
        true,
        llmPreferenceStore.podLogMaxLength,
        null,
        true
      );
    } catch (e) {
      console.log("getPodPreFailLogTool error=", e);
      log = await k8sApi.readNamespacedPodLog(
        name,
        namespace,
        null,
        false,
        true,
        llmPreferenceStore.podLogMaxLength,
      );
    }
    return log.body;
  },
  {
    name: "get_pod_pre_fail_log",
    description:
      "Get the Pod previous terminated container log by Pod Name And Namespace ",
    schema: z.object({
      name: z.string().describe("The name of the Pod"),
      namespace: z.string().describe("The namespace of the Pod"),
    }),
    verbose: true,
  }
);

export { getPodLogTool, getPodPreFailLogTool };
